package rjeutsky.database.jpa;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import rjeutsky.database.jpa.models.JPAPayment;
import rjeutsky.database.jpa.models.JPASubscription;
import rjeutsky.models.Payment;

public class JPAPaymentRepository extends BaseCRUDDomainRepository<Payment> {
	
	public JPAPaymentRepository(SessionFactory sessionFactory) {
		super(sessionFactory);
	}
	
	@Override
	public List<Payment> query() throws SQLException {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		
		@SuppressWarnings("unchecked")
		List<Payment> payments =  JPAPayment.getPayments(session.createQuery("from JPAPayment").list());
		
		session.getTransaction().commit();
		session.close();
		
		return payments;
	}

	@Override
	public void create(Payment item) throws SQLException {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		
		JPAPayment payment = new JPAPayment();
		payment.setPayedSum(item.getPayedSum());
		payment.setSubscription((JPASubscription) session.get(JPASubscription.class, item.getSubscriptionId()));
		session.save(payment);
		item.setId(payment.getId());
		
		session.getTransaction().commit();
		session.close();
	}

	@Override
	public Payment read(long id) throws SQLException {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		
		Payment payment = null;
		
		JPAPayment jpaPayment = (JPAPayment) session.get(JPAPayment.class, id);
		if (jpaPayment != null) {
			payment = jpaPayment.getPayment();
		}
		
		session.getTransaction().commit();
		session.close();
		return payment;
	}

	@Override
	public void update(Payment item) throws SQLException {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		
		JPAPayment payment = JPAPayment.getJPAPayment(session, item);
		if (payment != null) {
			payment.setPayedSum(item.getPayedSum());
			payment.setSubscription((JPASubscription) session.get(JPASubscription.class, item.getSubscriptionId()));
		}
		
		session.getTransaction().commit();
		session.close();
	}

	@Override
	public void delete(long id) throws SQLException {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		
		JPAPayment payment = (JPAPayment) session.get(JPAPayment.class, id);
		if (payment != null) {
			session.delete(payment);
		}
		
		session.getTransaction().commit();
		session.close();
	}

}
